package com.xixi.core.rpc.server.tcp;

import com.xixi.core.rpc.model.RpcRequest;
import com.xixi.core.rpc.model.RpcResponse;
import com.xixi.core.rpc.protocol.ProtocolMessage;
import com.xixi.core.rpc.protocol.ProtocolMessageDecoder;
import com.xixi.core.rpc.protocol.ProtocolMessageEncoder;
import com.xixi.core.rpc.protocol.ProtocolMessageTypeEnum;
import com.xixi.core.rpc.registry.LocalRegistry;
import io.vertx.core.Handler;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.net.NetSocket;

import java.io.IOException;
import java.lang.reflect.Method;

/**
 * @author: zxh
 * @date: 2024/8/26 15:52
 * @description: TCP请求处理器
 */
public class TcpServerHandler implements Handler<NetSocket> {
	@Override
	public void handle(NetSocket event) {

		TcpBufferHandlerWrapper bufferHandlerWrapper = new TcpBufferHandlerWrapper(buffer -> {
			ProtocolMessage<RpcRequest> message;
			try {
				System.out.println("开始数据解码：" + buffer.length());
				message = (ProtocolMessage<RpcRequest>) ProtocolMessageDecoder.decode(buffer);
				System.out.println("请求数据解码完成：");
			} catch (IOException e) {
				throw new RuntimeException("协议消息解码错误");
			}
			RpcRequest rpcRequest = message.getBody();

			// 构造相应结果对象
			RpcResponse rpcResponse = new RpcResponse();
			// 处理请求
			try {
				// 获取要调用的服务实现类，通过反射调用
				Class<?> implClass = LocalRegistry.get(rpcRequest.getServiceName());
				Method method = implClass.getMethod(rpcRequest.getMethodName(), rpcRequest.getParameterTypes());
				Object result = method.invoke(implClass.newInstance(), rpcRequest.getArgs());
				// 封装返回结果
				rpcResponse.setData(result);
				rpcResponse.setDataType(method.getReturnType());
				rpcResponse.setMessage("ok");
			} catch (Exception e) {
				e.printStackTrace();
				rpcResponse.setMessage(e.getMessage());
				rpcResponse.setException(e);
			}

			// 发送响应，编码
			ProtocolMessage.Header header = message.getHeader();
			header.setType((byte) ProtocolMessageTypeEnum.RESPONSE.getKey());
			ProtocolMessage<RpcResponse> responseProtocolMessage = new ProtocolMessage<>(header, rpcResponse);
			try {
				System.out.println("开始响应数据编码：");
				Buffer encodeBuffer = ProtocolMessageEncoder.encode(responseProtocolMessage);
				System.out.println("响应数据编码完成: " + encodeBuffer.length());
				event.write(encodeBuffer);
			} catch (IOException e) {
				throw new RuntimeException("协议消息编码错误");
			}
		});

		// 处理连接
		/*event.handler(buffer -> {
			ProtocolMessage<RpcRequest> message;
			try {
				System.out.println("开始数据解码：" + buffer.length());
				message = (ProtocolMessage<RpcRequest>) ProtocolMessageDecoder.decode(buffer);
				System.out.println("请求数据解码完成：");
			} catch (IOException e) {
				throw new RuntimeException("协议消息解码错误");
			}
			RpcRequest rpcRequest = message.getBody();

			// 构造相应结果对象
			RpcResponse rpcResponse = new RpcResponse();
			// 处理请求
			try {
				// 获取要调用的服务实现类，通过反射调用
				Class<?> implClass = LocalRegistry.get(rpcRequest.getServiceName());
				Method method = implClass.getMethod(rpcRequest.getMethodName(), rpcRequest.getParameterTypes());
				Object result = method.invoke(implClass.newInstance(), rpcRequest.getArgs());
				// 封装返回结果
				rpcResponse.setData(result);
				rpcResponse.setDataType(method.getReturnType());
				rpcResponse.setMessage("ok");
			} catch (Exception e) {
				e.printStackTrace();
				rpcResponse.setMessage(e.getMessage());
				rpcResponse.setException(e);
			}

			// 发送响应，编码
			ProtocolMessage.Header header = message.getHeader();
			header.setType((byte) ProtocolMessageTypeEnum.RESPONSE.getKey());
			ProtocolMessage<RpcResponse> responseProtocolMessage = new ProtocolMessage<>(header, rpcResponse);
			try {
				System.out.println("开始响应数据编码：");
				Buffer encodeBuffer = ProtocolMessageEncoder.encode(responseProtocolMessage);
				System.out.println("响应数据编码完成: " + encodeBuffer.length());
				event.write(encodeBuffer);
			} catch (IOException e) {
				throw new RuntimeException("协议消息编码错误");
			}
		});*/
		event.handler(bufferHandlerWrapper);
	}
}
